#include "FileTest.h"
#include <stdio.h>
#include <string.h>

/*
 * Created: 2/24/12; CGP
 
a) Create a new file (opened for writing)
b) Write multiple bytes of data into the file
c) Close the file
d) Close all other necessary disk structures (e.g., Directory)

e) Stop your test program from running

f) Restart your test program
g) Open the same file for reading
h) Read all the data & verify that the data was the same as expected.
i) Make sure that when you read past the end of the file, you can't read more data. 
    (i.e., End of File is detected correctly).
 */

#define NUMBER_WRITES 100

// Usage: without a cmd line arg, means part1, 
///    with a command line argument means part2
int main(int argc, char *argv[]) {
    int length;
    printf("Starting test...\n"); fflush(stdout);
    FileTest ft;
    const char *fileName = "test1";
    unsigned char data[] = "abcdefghijklmnopqrstuvwxyz";
    File *f1;

    if (argc == 1) {
        printf("Writing to file...\n");
        f1 = new File(fileName, "w");

        for (int i=0; i < NUMBER_WRITES; i++) {
            length = f1->Write(data + (i % 10), 1);
        }
        if (! f1->Close()) {
            printf("ERROR: Could not close file\n");
        }
        delete f1;
    } else {
        printf("Reading from file...\n");
        f1 = new File(fileName, "r");
        unsigned char buffer;
        for (int i=0; i < NUMBER_WRITES; i++) { // 38*26 bytes = 988 bytes
            length = f1->Read(&buffer, 1);
            
            if (length != 1) {
                printf("ERROR: Could not read back all bytes of file\n");
            }
            
            if (data[(i % 10)] != buffer) {
                printf("ERROR: Buffer is not equal to data written (expected= %c, actual= %c)\n",
                    data[i], buffer);
            }
        }
        
        length = f1->Read(&buffer, 1);
        if (length != 0) {
            printf("ERROR: End of file not correctly reached\n");
        }
        
        if (! f1->Close()) {
            printf("ERROR: Could not close file\n");
        }
        delete f1;
    }
}





